//路由控制器层
const utils = require(__basename + '/utils/utils.js')
const api = require(__basename + '/API/api.js')
    // const decode = require('jsonwebtoken')
const moment = require('moment')
const sequelize = require('sequelize')
const whitelist = require(__basename + '/whitelist/whitelist.js')
let Op = sequelize.Op
class routerController {
    //验证验证码
    validCode(req, res, next) {
            let url = req.url;
            if (whitelist.codelist.indexOf(url) > -1) {

                //需要验证验证码和邮箱
                let email = req.body.email;
                // console.log(req.body)
                let code = req.body.emailBox;
                let time = new Date().getTime() - 10 * 60 * 1000
                let date = moment(time).format('YYYY-MM-DD HH:mm:ss')
                api.findData('Code', {
                    email,
                    code,
                    created_at: {
                        [Op.gte]: date
                    }
                }).then(result => {
                    console.log(result)
                    if (result.length == 0) {
                        res.send({ msg: '验证码错误' })
                    } else {
                        next()
                    }
                }).catch(err => {
                    console.log(err)
                    res.send('验证码无效')
                })

            } else {
                next();
            }
        }
        //登录验证
    validLogin(req, res, next) {
            // console.log(req.url)
            let url = req.url.split('?')[0]
                // console.log(url)
            if (whitelist.tokenList.indexOf(url) > -1) {
                //截取token
                let token = req.body.token ? req.body.token : req.query.token;
                //需要验证token
                // console.log(token)
                utils.verifyToken(token, (err, decode) => {
                    if (err) {
                        console.log(err)
                        res.send({ msg: '请先登录', code: 303 });
                    } else {
                        console.log('decode ==> ', decode);
                        req.email = decode.data;
                        next();
                    }
                })

            } else {
                next();
            }
        }
        //注册
    register(req, res) {
            let password = utils.encodeString(req.body.password)
            console.log(password)
                //生曾用户id
            let userId = 'u' + new Date().getTime()
            let o = {
                userId,
                password,
                user: req.body.user,
                email: req.body.email,
            };
            //检测邮箱已经被注册
            api.findData('User', { email: req.body.email }, ['user']).then(result => {
                console.log(result)
                if (result.length == 0) {
                    api.createData('User', o).then((result) => {
                        res.send({ msg: '注册成功', code: 200, result })
                    }).catch(err => {
                        console.log(err);
                        res.send({ msg: '注册失败', code: 150 })
                    })
                } else {
                    res.send({ msg: '邮箱已经被注册' })
                }
            }).catch(err => {
                console.log(err);
                res.send({ msg: '失败', code: 102 })
            })

        }
        //s发邮箱
    getCode(req, res) {
            let email = req.body.email
            let code = Math.random().toString().substr(2, 6)
            api.createData('Code', {
                email,
                code,
            }).then(result => {
                utils.sendEmail(email, code, (err, data) => {
                    if (err) {
                        res.send({ msg: '获取失败' })
                    } else {
                        console.log(data)
                        res.send({ msg: '获取成功' })
                    }
                })
                res.send({ msg: '获取成功' })
            }).catch(err => {
                console.log(err)
                res.send({ msg: '获取失败' })
            })
        }
        //登录
    login(req, res) {
            console.log(req.body);
            api.findData('User', { email: req.body.email }, ['userId', 'password']).then(result => {
                console.log(result);
                if (result.length == 0) {
                    res.send({ msg: '该邮箱还没有被注册' })
                } else {
                    //密码匹配
                    let password = utils.encodeString(req.body.password);
                    if (password == result[0].dataValues.password) {
                        // console.log(req.body.email)
                        let token = utils.signToken(req.body.email, '0.5h')
                        res.send({ msg: '密码正确，登录成功！', token, code: 1010 })
                    } else {
                        res.send({ msg: '密码不正确，登录失败!' })
                    }
                }
                res.send('ok').catch(err => {
                    console.log(err)
                    res.send({ msg: '登录失败！' })
                })
            })
        }
        // userInfo(req, res) {
        //     console.log(req.email)
        //         // res.send('12300')
        //     api.findData('user', {
        //         email: req.email
        //     }, ['url']).then(result => {
        //         console.log(result)
        //         res.send({ msg: '查询成功，，', result })
        //     }).catch(err => {
        //         console.log(err)
        //         rs.send({ msg: "查询用户信息失败！" })
        //     })
        // }
    userInfo(req, res) {
            api.findData('User', {
                email: req.email
            }, ['user', 'url']).then(result => {
                res.send({ msg: '查询用户信息成功', code: 400, result });
            }).catch(err => {
                console.log('err ==> ', err);
                res.send({ msg: '查询用户信息失败', code: 401 });
            })
        }
        //添加商品类型方法
    addType(req, res) {
            let ShopTypeId = '_t' + new Date().getTime();
            api.createData('ShopType', {
                email: req.email,
                ShopTypeId,
                ShopTypeName: req.body.typename
            }).then(result => {
                // console.log(result)
                res.send({ msg: '添加商品类型成功' })
            }).catch(err => {
                console.log(err);
                res.send({ msg: '错误！' })
            })
        }
        //查询商品类型数据方法
    findTypeData(req, res) {
            // "AND `shop_type_name` LIKE '%服%'"
            let sql = "select * FROM `shoptype` WHERE   `email` = :email  "
            if (req.query.typename) {
                sql += "  AND `shop_type_name` LIKE '%" + req.query.typename + "%'"
            }
            sql += "  LIMIT :offset, :count"
            api.query(sql, {
                //用来替换：email为我们的req.email
                email: req.email,
                offset: Number(req.query.offset),
                count: Number(req.query.count),
            }).then(result => {
                // console.log(resutl)
                res.send({ msg: '查询数据类型成功', result })
            }).catch(err => {
                console.log(err)
                res.send({ msg: '查询失败！' })
            })
            console.log(req.query)
        }
        //编辑商品类型
    editType(req, res) {
            console.log(req.body)
            api.updateData('ShopType', {
                ShopTypeName: req.body.typename
            }, {
                ShopTypeId: req.body.typeId
            }).then(result => {
                console.log(result)
                res.send({ msg: "更新数据类型成功！", result, code: 111 })
            }).catch(err => {
                console.log(err)
                res.send({ msg: '更新数据失败，您可以重新尝试！' })
            })
        }
        //禁用商品类型
    disableType(req, res) {
            // console.log(token)
            api.updateData('ShopType', {
                Status: 0,
            }, {
                ShopTypeId: req.body.typeId,
                email: req.email,
            }).then(result => {
                console.log(result)
                res.send({ msg: '禁用商品类型成功！' })
            }).catch(err => {
                console.log(err)
                res.send({ msg: '禁用商品类型失败！' })
            })

        }
        //启用商品类型
    enableType(req, res) {
            api.updateData('ShopType', {
                Status: 1,
            }, {
                ShopTypeId: req.body.typeId,
                email: req.email,
            }).then(result => {
                console.log(result)
                res.send({ msg: '启用商品类型成功！' })
            }).catch(err => {
                console.log(err)
                res.send({ msg: '启用商品类型失败！' })
            })

        }
        //删除商品类型
    removeData(req, res) {
            api.removeData('ShopType', {
                ShopTypeId: req.body.typeId,
                email: req.email
            }).then(result => {
                // console.log(result)
                res.send({ msg: '删除商品类型成功！', code: 999 })
            }).catch(err => {
                console.log(err)
                res.send({ msg: '删除商品类型失败！' })
            })
        }
        //查询商品类型总数量
    count(req, res) {
        api.count('ShopType', {
            email: req.email
        }).then(result => {
            console.log(result)
            res.send({ msg: '查询总商品类型成功！', code: 299, result })
        }).catch(err => {
            console.log(err)
            res.send({ msg: '查询总商品类型失败！' })
        })
    }
}
module.exports = new routerController